package com.ask.forMe.langchain4j.tools;

import com.ask.forMe.config.UserContextHolder;
import com.ask.forMe.model.entity.Order;
import com.ask.forMe.model.entity.Result;
import com.ask.forMe.model.entity.UserContext;
import com.ask.forMe.service.ItemService;
import com.ask.forMe.service.OrderService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class XiaozhiAgentTools {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ItemService itemService;

    @Tool(name = "订单查询", value = "根据用户提供的订单号查询订单信息， 当用户的输入包含隐私和敏感信息时，如身份证号码，警告用户并拒绝执行请求")
    public Result queryOrder(@P(value = "订单号") String orderNum) {
        log.info("进入订单查询接口，当前线程:{}", Thread.currentThread().getName());
        UserContext userContext = UserContextHolder.getUserContext();
        Long userId = userContext.getUserId();
        if (!userContext.hasPermission("READ:ORDER"))
            return Result.fail("您没有查询订单的权限！");

        Order order = orderService.queryByOrderNum(orderNum);
        if (order == null)
            return Result.fail("定单不存在！");

        if (!order.getUserId().equals(userId) && !userContext.hasPermission("READ:ORDER:AMY"))
            return Result.fail("您无权查看此订单！");
        return Result.success(order);
    }

    @Tool(name = "取消订单", value = "帮助用户取消订单")
    public Result cancelOrder(@P(value = "订单号") String orderNum) {
        return orderService.cancelOrder(orderNum);
    }

    @Tool(name = "查询所有商品", value = "当需要商品相关信息时，调用此接口")
    public Result queryItems() {
        log.info("调用接口：查询所有商品");
        return Result.success(itemService.list());
    }

    @Tool(name = "商品详情", value = "商品详情： 从上下文中提取出商品itemId，用于查询商品详情")
    public Result queryItemById(@P(value = "商品id") Long itemId) {
        log.info("进入查询商品详情接口...");
        return Result.success(itemService.getById(itemId));
    }


    @Tool(name = "始终执行的方法", value = "无论用户输入什么内容，此方法都一定会执行")
    public Result transferToHuman() {
        System.out.println("转人工！");
        return Result.success("转人工！");
    }

    @Tool(value = "检测用户情绪，但你认为用户不耐烦时，调用此方法")
    public String handleNegativeEmotion(String userId, int emotionScore) {
        System.out.println("用户不耐烦");
        return "转至人工接口1";
    }

    @Tool(value = "检测用户情绪，但你认为用户很生气时，调用此方法")
    public String handleNegativeEmotion1(String userId, int emotionScore) {
        System.out.println("很生气");
        return "转至人工接口2";
    }




}
